trigger Contact_UpdateContactCountOnAccount on Contact (after delete, after insert, after undelete, 
after update) {
	if(LeadSync_AsyncApex.firstCount == true){
		LeadSync_AsyncApex.firstCount = false;
	// Build the list of Accounts to Update
	set<Id> AccountIDs = new Set<Id>();
	if(Trigger.isInsert || Trigger.isUnDelete){
		for(Contact c : Trigger.new){
			if(c.AccountID <> null) AccountIDs.add(c.AccountID);
		}
	}
	
	if(Trigger.isUpdate){
		for(Integer i = 0; i<Trigger.New.size();I++){
			// Only add it if there is an account and it has changed, or the Contact Status has changed
			if(Trigger.New[i].AccountID <> null && Trigger.New[i].Status__c<> Trigger.Old[i].Status__c && Trigger.New[i].AccountID == Trigger.Old[i].AccountID){
				AccountIDs.add(Trigger.New[i].AccountID);
			}
			if(Trigger.New[i].AccountID <> Trigger.Old[i].AccountID){
				if(Trigger.New[i].AccountID <> null) AccountIDs.add(Trigger.New[i].AccountID);
				if(Trigger.Old[i].AccountID <> null) AccountIDs.add(Trigger.Old[i].AccountID);
			}
				
		}
	}
	
	if(Trigger.isDelete){
		for(Contact c : Trigger.old){
			if(c.AccountID <> null) AccountIDs.add(c.AccountID);
		}
	}
	
	// Update the Accounts
	if(AccountIDs.size()>0){
		list<Account> AccountsToUpdate = new List<Account>();
		List<AggregateResult> ContactCounts = [select AccountID acct, count(Id) from Contact where AccountID in :AccountIDs and Valid_Contact__c = 'True' group by AccountID];
	    for(AggregateResult r : ContactCounts){
            try{
            		System.Debug('======================> Account ID: '+r.get('acct'));
            		System.Debug('======================> Contacts: '+r.get('expr0'));
            		Id AccountID = string.valueOf(r.get('acct'));
            		Integer count = Integer.valueOf(r.get('expr0'));
            		AccountsToUpdate.add(new Account(Id=AccountID, Contacts__c = count));
            		AccountIDs.remove(AccountID);
            }catch(exception e){}
        }
        if(AccountIDs.size()>0){ // Then there are some Accounts with no Contacts
        	for(Id AccountID : AccountIDs){
        		AccountsToUpdate.add(new Account(Id=AccountID, Contacts__c = 0));
        	}
        }
		update AccountsToUpdate;
	} 
	}
}